﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CloudApiServer.helper;
using Newtonsoft.Json;

namespace CloudApiServer.Services
{
    /// <summary>
    /// 人员信息服务
    /// </summary>
    public class FsiPsnInfoService
    {
        /// <summary>
        /// 1101 查询人员信息
        /// </summary>
        /// <param name="fsiRequest">查询人员信息入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>查询人员信息返参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<outputQueryPsnInfo> QueryPsnInfo(FsiRequestHeader<InputQueryPsnInfoRequest> fsiRequest, string ControllerName)
        {
            try
            {
                string cert_no = "";
                string fsiadmvs = fsiRequest.mdtrtarea_admvs.Substring(0, 2);
                //如果是从江苏医保且强制身份证有值 则取强制身份证的这个值
                if (!string.IsNullOrEmpty(FsiDatainfo.JiangsuDefautlcardno) && ControllerName == "FsiApiJiangsuJiangxiController")
                {
                    cert_no = FsiDatainfo.JiangsuDefautlcardno;
                }
                else
                {
                    //电子凭证的时候传certno 身份证号码
                    if (fsiRequest.Input.data.mdtrt_cert_type == "01")
                    {
                        cert_no = fsiRequest.Input.data.certno;
                    }
                    else
                    {
                        //如果是身份证，且从浙江控制器传入，且区划为陕西，则通过入参分割获取身份证号
                        if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "61" && fsiRequest.Input.data.mdtrt_cert_type == "03")
                        {
                            string[] parts = fsiRequest.Input.data.mdtrt_cert_no.Split('|');
                            cert_no = parts.Length > 4 ? parts[4] : null;
                        }
                        //如果是身份证，且从浙江控制器传入，且区划为浙江，从证件号码获取身份证号
                        else if (ControllerName == "FsiApiZheJiangController" && fsiadmvs == "33" && fsiRequest.Input.data.mdtrt_cert_type == "03")
                        {
                            cert_no = fsiRequest.Input.data.certno;
                        }
                        else
                        {
                            cert_no = fsiRequest.Input.data.mdtrt_cert_no;
                        }
                    }
                }

                //最后 如果拿到的证件号为空，则使用默认的证件号
                if (string.IsNullOrEmpty(cert_no))
                {
                    cert_no = FsiDatainfo.Defautlcardno;
                }
                //读取缓存
                if (ApiDatainfo.stateRedis)
                {
                    var key = $"{cert_no}";
                    string value = await RedisHelper.GetAsync(key,group:"psninfo",dbIndex:ApiDatainfo.redisDb);
                    if (!string.IsNullOrEmpty(value))
                    { 
                        return JsonConvert.DeserializeObject<outputQueryPsnInfo>(value);
                    }
                }

                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                string query = $"select * from fsi_PsnInfo where certno=@certno";
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@certno", cert_no),
                };
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                if (dt.Rows.Count == 1)
                {
                    List<Idetinfo> list = new List<Idetinfo>();
                    Random rnd = new Random();
                    DateTime dateTime = DateTime.Now;
                    var output = new outputQueryPsnInfo
                    {
                        baseinfo = new Baseinfo
                        {
                            certno = dt.Rows[0]["certno"].ToString(),
                            psn_no = dt.Rows[0]["psn_no"].ToString(),
                            gend = dt.Rows[0]["gend"].ToString(),
                            exp_content = dt.Rows[0]["exp_content"].ToString(),
                            brdy = dt.Rows[0]["brdy"].ToString(),
                            naty = dt.Rows[0]["naty"].ToString(),
                            psn_cert_type = dt.Rows[0]["psn_cert_type"].ToString(),
                            psn_name = dt.Rows[0]["psn_name"].ToString(),
                            age = PublicMethod.CalculateAge(dt.Rows[0]["brdy"].ToString(), dateTime),
                            psn_mgtcode = dt.Rows[0]["psn_mgtcode"].ToString()
                        },
                        insuinfo = new List<Insuinfo>
                        {
                            new Insuinfo
                            {
                                insuplc_admdvs = dt.Rows[0]["insuplc_admdvs"].ToString(),
                                psn_insu_date = dt.Rows[0]["psn_insu_date"].ToString(),
                                cvlserv_flag = dt.Rows[0]["cvlserv_flag"].ToString(),
                                balc = Convert.ToDouble(dt.Rows[0]["balc"]),
                                emp_name = dt.Rows[0]["emp_name"].ToString(),
                                psn_type = dt.Rows[0]["psn_type"].ToString(),
                                psn_insu_stas = dt.Rows[0]["psn_insu_stas"].ToString(),
                                insutype = dt.Rows[0]["insutype"].ToString(),
                                paus_insu_date = dt.Rows[0]["paus_insu_date"].ToString()
                            }
                        },
                        idetinfo = new List<Idetinfo>
                        {
                            new Idetinfo
                            {
                                psn_idet_type = dt.Rows[0]["psn_idet_type"].ToString(),
                                psn_type_lv = dt.Rows[0]["psn_type_lv"].ToString(),
                                memo = dt.Rows[0]["memo"].ToString(),
                                begntime = dt.Rows[0]["begntime"].ToString(),
                                endtime = dt.Rows[0]["endtime"].ToString(),
                            }
                        }
                    };
                    //写入缓存
                    if (ApiDatainfo.stateRedis)
                    {
                        var key = $"{cert_no}";
                        await RedisHelper.SetAsync(key, JsonConvert.SerializeObject(output), TimeSpan.FromMinutes(ApiDatainfo.redisExpirationtime),group:"psninfo",dbIndex:ApiDatainfo.redisDb);
                    }
                    return output;
                }
                else
                {
                    throw new Exception($"查询人员信息表失败！根据传入的证件号【{cert_no}】查询到的人员信息总数为：{dt.Rows.Count},如需调用默认人员信息，请使用身份证读卡并且不填写证件号码或填写【1】后发起请求！如需新增人员信息，请访问web/index.html使用【医保人员信息插入】功能新增！");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[FsiPsnInfoService.QueryPsnInfo]人员信息获取异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
        /// <summary>
        /// 2001 人员待遇享受检查
        /// </summary>
        /// <param name="fsiRequest">查询人员信息入参</param>
        /// <param name="ControllerName">来源控制器名称</param>
        /// <returns>查询人员信息返参</returns>
        /// <exception cref="Exception"></exception>
        public async Task<OutputQueryPsnPriorityInfo> QueryPsnPriorityInfo(FsiRequestHeader<InputQueryPsnPriorityInfo> fsiRequest, string ControllerName)
        {
            try
            {
                string psn_no = fsiRequest.Input.data.psn_no;
                string begntime =  fsiRequest.Input.data.begntime;
                string endtime = fsiRequest.Input.data.endtime; 
                if (string.IsNullOrEmpty(psn_no) || string.IsNullOrEmpty(begntime) )
                {
                    throw new Exception("参数校验失败：传入的人员编号|开始日期为空，请检查入参！");
                }
                List<OutputQueryPsnPriorityInfoTrtinfoList> trtinfoList = new List<OutputQueryPsnPriorityInfoTrtinfoList>();
                string connectionString = $"Database={ApiDatainfo.mysqlDatabase};Data Source={ApiDatainfo.mysqlUrl};Port={ApiDatainfo.mysqlPost};UserId={ApiDatainfo.mysqlUser};Password={ApiDatainfo.mysqlPwd};Charset=utf8mb4;TreatTinyAsBoolean=false;Allow User Variables=True";
                string query = "select * from fsi_querypsnpriorityinfo where begndate>=@begndate and psn_no=@psn_no";

                if (!string.IsNullOrEmpty(endtime))
                {
                    query += " and enddate<=@enddate";
                }
                var parameter = new List<MySqlParameter>
                {
                    new MySqlParameter("@begndate", begntime),
                    new MySqlParameter("@enddate", endtime),
                    new MySqlParameter("@psn_no",psn_no),
                };
                DataTable dt = await MySqlHelper.ExecuteQueryAsync(connectionString, query, parameter);
                if (dt.Rows.Count ==0)
                {
                    throw new Exception($"获取人员享受待遇数据失败！根据传入的时间范围【{begntime}】-【{endtime}】未查询到人员编号为【{psn_no}】的记录！");
                }

                foreach (DataRow row in dt.Rows)
                {
                    var trtinfo = new OutputQueryPsnPriorityInfoTrtinfoList
                    {
                        begndate = row["begndate"].ToString(),
                        fund_pay_type = row["fund_pay_type"].ToString(),
                        enddate = row["enddate"].ToString(),
                        psn_no = row["psn_no"].ToString(),
                        exp_content = row["exp_content"].ToString(),
                        trt_enjymnt_flag = row["trt_enjymnt_flag"].ToString(),
                    };
                    trtinfoList.Add(trtinfo);
                }
                return new OutputQueryPsnPriorityInfo()
                {
                    trtinfo = trtinfoList
                };
            }
            catch (Exception ex)
            {
                LogHelper.Error($"[FsiPsnInfoService.QueryPsnPriorityInfo]人员待遇检查查询发生异常，错误内容：{ex.Message} 异常堆栈{ex.StackTrace}");
                throw;
            }
        }
    }
}
